﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using MiscUtil.IO;

namespace TlvLib.PacketParsers
{
    public class CameraStatusReportPacketParser : PacketParserBase
    {
        public override bool CanParse(RawPacket packet)
        {
            return packet.MessageId == PacketType.CameraStatusReport;
        }

        public override object Parse(RawPacket packet)
        {
            if (packet.Payload == null)
            {
                throw new ArgumentNullException("PayLoad");
            }

            if (packet.Payload.Length == 0)
            {
                throw new ArgumentException("Paylod长度为0");
            }

            using (var stream = new MemoryStream(packet.Payload))
            using (var reader = new EndianBinaryReader(Config.EndianBitConverter, stream))
            {
                var monitorIdBuffer = reader.ReadBytes(32);
                var count = CountNonZero(monitorIdBuffer);
                var monitorId = AsciiEncoding.GetString(monitorIdBuffer, 0, count);

                var directionBuffer = reader.ReadBytes(8);
                count = CountNonZero(directionBuffer);
                var directionNo = AsciiEncoding.GetString(directionBuffer, 0, count);

                var cameraId = reader.ReadInt32();
                var ip = reader.ReadInt32();
                var ipString = new IPAddress(ip).ToString();
                System.Diagnostics.Debug.WriteLine(ipString);

                var detectMethod = reader.ReadByte();
                var state = reader.ReadByte();

                var cs = new Packets.CameraStatus();
                cs.CameraId = cameraId;
                cs.DetectMethod = detectMethod;
                cs.DirectionNo = directionNo;
                cs.Ip = ipString;
                cs.StateCode = state;
                cs.StationId = monitorId;

                return cs;
            }
        }
    }
}
